#include "core/MethodObfuscator.h"
#include "core/WhitelistManager.h"
#include "utils/RandomGenerator.h"
#include <QFile>
#include <QTextStream>
#include <QRegularExpression>

MethodObfuscator::MethodObfuscator() {}
MethodObfuscator::~MethodObfuscator() {}

QMap<QString, QString> MethodObfuscator::generateMappings(const QStringList &files, WhitelistManager *whitelist)
{
    QMap<QString, QString> mappings;
    // 简单实现：对每个文件提取简单的方法名占位映射
    for (const QString &file : files) {
        QStringList methodNames = extractMethodNames(file);
        for (const QString &name : methodNames) {
            if (name.isEmpty()) continue;
            QString obfuscated = generateObfuscatedName(name);
            if (shouldObfuscate(name, whitelist)) {
                mappings.insert(name, obfuscated);
            }
        }
    }
    return mappings;
}

QStringList MethodObfuscator::extractMethodNames(const QString &filePath)
{
    QStringList methods;
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        return methods;
    }
    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        // 简单匹配 C/C++/Objective-C 风格的函数声明/实现行，粗略提取名字
        QRegularExpression rx("\\b([A-Za-z_][A-Za-z0-9_]+)\\s*\\(");
        QRegularExpressionMatch match = rx.match(line);
        if (match.hasMatch()) {
            QString cand = match.captured(1);
            if (!cand.isEmpty()) {
                methods << cand;
            }
        }
    }
    file.close();
    // 去重
    methods.removeDuplicates();
    return methods;
}

QString MethodObfuscator::generateObfuscatedName(const QString &originalName)
{
    RandomGenerator gen;
    return gen.generateIdentifier(8);
}

bool MethodObfuscator::shouldObfuscate(const QString &methodName, WhitelistManager *whitelist)
{
    return whitelist ? !whitelist->isWhitelisted(methodName) : true;
}